using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace TmxUtil
{
    public class SolutionParser
    {
        public static Solution Parse(string slnFile)
        {
            Solution ret = new Solution(slnFile);

            using(FileStream fs = new FileStream(slnFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            using(StreamReader sr = new StreamReader(fs, Encoding.Default))
            {
                for(string s = sr.ReadLine(); s != null; s = sr.ReadLine())
                {
                    string[] arr = s.Split(new char[] {'=', ','});
                    if (arr.Length >= 4 && arr[0].StartsWith("Project("))
                    {
                        string name = TrimQ(arr[1]);
                        string file = TrimQ(arr[2]);
                        bool isGuid = false;
                        try
                        {
                            new Guid(TrimQ(arr[3]));
                            isGuid = true;
                        }
                        catch
                        {
                        }

                        if (isGuid)
                        {
                            Project p = new Project(ret, name, file);
                            if (File.Exists(p.FullName))
                                ret.Projects.Add(p);
                        }
                    }
                }
            }

            ret.Projects.Sort(delegate(Project x, Project y) { return x.File.CompareTo(y.File); });
            return ret;
        }

        static string TrimQ(string s)
        {
            return s.Trim().Trim('\"');
        }
    }
}
